/* 
    动态网站 练习
*/


const http = require('http');
const path = require('path');
const fs = require('fs');
const querystring = require('querystring');
const scoresData = require('./scores.json');

http.createServer((req, res) => {
    // 查询 获取静态资源 /query
    if (req.url.startsWith('/query') && req.method == 'GET') {
        fs.readFile(path.join(__dirname, 'view', 'index.html'), 'utf8', (err, data) => {
            if (err) {
                res.write(500, {
                    "Content-Type": "text/plain; charset=utf8"
                });
                res.end('服务器出错啦，请联系管理员');
            }
            res.end(data);
        });
    } else if (req.url.startsWith('/score') && req.method == 'POST') {
        // 获得成绩 /score
        let pdata = '';
        req.on('data', (chunk) => {
            pdata += chunk;
        });
        req.on('end', () => {
            let obj = querystring.parse(pdata);
            let result = scoresData[obj.code];
            fs.readFile(path.join(__dirname, 'view', 'result.html'), 'utf8', (err, data) => {
                if (err) {
                    res.write(500, {
                        "Content-Type": "text/plain; charset=utf8"
                    });
                    res.end('服务器出错啦，请联系管理员');
                }
                data = data.replace('$$chinese$$', result.chinese);
                data = data.replace('$$math$$', result.math);
                data = data.replace('$$english$$', result.english);
                data = data.replace('$$summary$$', result.summary);
                res.end(data);
            });

        });

    }


}).listen(3000, () => {
    console.log('running……');
});
